using UnityEngine;

namespace MiningGame
{
    [RequireComponent(typeof(PolygonCollider2D))]
    public class MeshDeformationGround : MonoBehaviour
    {
        public float destructionRadius = 0.5f;

        private PolygonCollider2D polyCollider;
        private Vector2[] originalPoints;

        void Start()
        {
            polyCollider = GetComponent<PolygonCollider2D>();
            originalPoints = polyCollider.points.Clone() as Vector2[];
        }

        void OnCollisionEnter2D(Collision2D collision)
        {
            Debug.LogError("OnCollisionEnter2D detected with: " + collision.gameObject.name);
        }

        void OnCollisionStay2D(Collision2D collision)
        {
            Debug.LogError("OnCollisionStay2D detected with: " + collision.gameObject.name);
            if (collision.gameObject.CompareTag("Drill"))
            {
                ContactPoint2D contact = collision.contacts[0];
                DeformGround(contact.point);
            }
        }

        void DeformGround(Vector2 drillPosition)
        {
            Vector2[] points = polyCollider.points;
            Vector2 localPos = transform.InverseTransformPoint(drillPosition);

            for (int i = 0; i < points.Length; i++)
            {
                float distance = Vector2.Distance(localPos, points[i]);
                if (distance < destructionRadius)
                {
                    // 将点向内推
                    Vector2 direction = (points[i] - localPos).normalized;
                    points[i] += direction * (destructionRadius - distance) * 0.5f;
                }
            }

            polyCollider.SetPath(0, points);

            // 更新视觉表现
            UpdateMesh();
        }

        void UpdateMesh()
        {
            // 这里需要根据collider的点重新生成mesh
            // 可以使用PolygonCollider2D的路径创建mesh
        }

        public void ResetGround()
        {
            polyCollider.SetPath(0, originalPoints);
            UpdateMesh();
        }
    }
}